package common.hotupdate;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;

public class JarCreate {

    private static final int BUFFER_SIZE = 2048;

    public static void toJar(String srcDir, OutputStream out, boolean keepDirStructure) {
        long start = System.currentTimeMillis();
        JarOutputStream jos = null;
        try {
            jos = new JarOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, jos, sourceFile.getName(), keepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("jar打包成功，耗时：" + (end - start) + " ms");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (jos != null) {
            try {
                jos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void compress(File sourceFile, JarOutputStream jos, String name, boolean keepDirStruct) throws IOException {
        byte[] buff = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            //想jar输出流中添加一个jar实体，构造器中name 为jar实体的文件名字
            jos.putNextEntry(new ZipEntry(sourceFile.getName()));
            FileInputStream in = new FileInputStream(sourceFile);
            int len;
            while ((len = in.read(buff)) != -1) {
                jos.write(buff, 0, len);
            }
            jos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                //需要保留原来的文件结构时，需要对空文件夹进行处理
                if (keepDirStruct) {
                    //空文件夹的处理
                    jos.putNextEntry(new ZipEntry(name));
                    //没有文件，不需要文件的copy
                    jos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    //是否需要保留原来的文件结构
                    if (keepDirStruct) {
                        //注意：file.getName()前面需要带上父文件夹的名字加斜杠
                        //不然最后压缩包中就不能保留原来的文件结构，即：所有问价你都跑到压缩包根目录下了
                        compress(file, jos, name + "/" + file.getName(), keepDirStruct);
                    } else {
                        compress(file, jos, file.getName(), keepDirStruct);
                    }
                }
            }
        }
    }
}
